package es.udc.emarketapp.http.controller.actions.products;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessages;

import es.udc.emarketapp.emarket.model.product.vo.ProductVO;
import es.udc.emarketapp.emarket.model.productFacade.ProductFacade;
import es.udc.emarketapp.http.controller.session.SessionManager;
import es.udc.emarketapp.http.view.actionForms.ProductForm;
import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.struts.action.DefaultAction;
import org.apache.struts.upload.FormFile;

public class CreateProductAction extends DefaultAction {

    public ActionForward doExecute(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException, InternalErrorException {

        ActionMessages errors = new ActionMessages();

        /* Get data. */

        ProductForm createProductForm = (ProductForm) form;

        Long idCat = createProductForm.getIdCat();

        String name = createProductForm.getName();
        String description = createProductForm.getDescription();
        double price = createProductForm.getPriceAsDouble();
        double weight = createProductForm.getWeightAsDouble();
        String country = createProductForm.getCountry();
        Long uds = createProductForm.getUdsAsLong();
        FormFile imageFile = createProductForm.getImage();
        byte[] image = imageFile.getFileData();

        byte[] imageIn = null;
        if (image.length > 0) {
            imageIn = image;
        }



        /* Create product*/

        try {

            ProductFacade productFacade = new ProductFacade();


            ProductVO productVO = new ProductVO(SessionManager.getIdUser(request), 
            		idCat, name, description, country, uds, imageIn, price, 
            		weight, true);

            /*
             * Insert the ProductVO in the database, and the returned ProductVO
             * (which contains the product identifier) in the request.
             */

            ProductVO insertedProductVO = productFacade.createProduct(productVO);

            request.setAttribute("product", insertedProductVO);

           

        } catch (InternalErrorException e) {
            System.out.println("Error al crear producto " + e);
        }


        /* Return ActionForward. */
        if (errors.isEmpty()) {
            return mapping.findForward("success");
        } else {
            saveErrors(request, errors);
            return new ActionForward(mapping.getInput());
        }
    }
}
